package com.atguigu.gmall.item.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.item.service.LockService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sound.sampled.Port;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.ReentrantLock;

@RestController
@Slf4j
public class LockController {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Value("${server.port}")
    String port;

    @Autowired
    LockService lockService;

    int i = 0;

    ReentrantLock lock = new ReentrantLock();

//    CountDownLatch countDownLatch = new CountDownLatch(10000);

    @GetMapping("/incr")
    public Result incrWithDistLock() throws InterruptedException {
        //分布式锁利用setnx指令，让redis在没有这个key的时候插入这个key，有就无操作



        String uuid = lockService.lock(); //自旋锁
        //取数字
        String num = redisTemplate.opsForValue().get("num");
        //对数字加1
        num = Integer.parseInt(num) + 1 + "";
        //加完以后修改给远程
        redisTemplate.opsForValue().set("num",num);
        lockService.unlock(uuid); //解锁
        return Result.ok();
    }

//    @GetMapping("/incr")
    public Result incrWithLocalLock() {
        log.info("端口:{}", port);

        lock.lock();

        //1、从远程获取一个数字
        String num = redisTemplate.opsForValue().get("num");
        //2、对这个数字加1并保存到redis
        num = Integer.parseInt(num) + 1 + "";
        redisTemplate.opsForValue().set("num",num);

        lock.unlock();

        return Result.ok();

    }

}
